﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using CardLogistics.Model.Purchase;
using System.Data;
using System.Text;

namespace CardLogistics.Web.MainPage.Purchase.Contract
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.Purchase.Purchase_ContractData DAL = new DAL.Purchase.Purchase_ContractData();
        private static readonly CardLogistics.DAL.Purchase.Purchase_Contract_detailData DetailDAL = new DAL.Purchase.Purchase_Contract_detailData();
        protected string TitleName = "";//显示的标题
        protected Dictionary<string, string> BasicTypeList = null;//芯片类型
        protected void Page_Load(object sender, EventArgs e)
        {
            BasicTypeList = GetBasicTypeList();
            if (!IsPostBack)
            {
                SIGNDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//签订日期
                BEDATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//生效日期
                CONPIC.Value = LoggedUser.USERFULLNAME;//订单负责人默认为当前登录用户
                TitleName = GetStatusInfo(-1, "采购合同");
                BindDLL(ddlSUPPID, "BASIC_SUPPLIERS", "SUPPLIERSNAME", "SUPPLIERSID", " and STATUS=0 and ISDELETE=0");  //供应商
                BindDLL(ddlBUYTYPEID, "BASIC_BASICTYPE", "TYPENAME", "ID", " and TYPENO=1 and STATUS=0 and ISDELETE=0");  //采购类型

                InitControl();
            }
        }
        #region 芯片类型
        /// <summary>
        /// 芯片类型
        /// </summary>
        /// <returns></returns>
        protected Dictionary<string, string> GetBasicTypeList()
        {
            Dictionary<string, string> cardTypeList = new Dictionary<string, string>();
            DataTable dt = CardLogistics.DAL.DbHelperSQL.GetQueryResult("select id,typename,ChipModel from basic_basictype where typeno=0 and STATUS=0 and ISDELETE=0");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string chipmodel = dt.Rows[i]["ChipModel"].ToString();//芯片型号
                 string typename="";
                if (string.IsNullOrEmpty(chipmodel))
                    typename = dt.Rows[i]["typename"].ToString();//显示类型名称
                else
                   typename= dt.Rows[i]["typename"].ToString() + "-" + dt.Rows[i]["ChipModel"].ToString();//显示类型名称和芯片型号

                cardTypeList.Add(id, typename);
            }
            return cardTypeList;
        }
        #endregion

        #region 编辑时得到一个对象实体
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public void InitControl()
        {
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    Purchase_Contract cData = DAL.GetModel(_key);
                    SetWebControls(this.Page, cData);
                    ddlSUPPID.Value = cData.SUPPID;//供应商
                    ddlBUYTYPEID.Value = cData.BUYTYPEID;//采购类型
                    hf_DEMANDID.Value = cData.DEMANDID;//需求单id

                    DataTable dt = DetailDAL.GetInfoByConId(_key);

                    string detId = "";
                    //dt.DefaultView.Sort = "BatchNo ASC";
                    DataView dv = dt.DefaultView;
                    dv.Sort = "BatchNo ASC";//按批次号排序
                    dt = dv.ToTable();
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detId += dr["BATCHNO"].ToString() + ";" + dr["CHIPID"].ToString() + ";" + dr["COSVERSION"].ToString() + ";" + dr["PRICE"].ToString() + ";" + dr["CARDAMOUNT"].ToString() + ";" + dr["SPAREPARTS"].ToString() + ";" + dr["PREMIUMS"].ToString() + ";" + dr["FIRSTPAY"].ToString() + ";" + dr["ACCEPTANCE"].ToString() + ";" + dr["QUALITYASSURANCE"].ToString() + "|";
                        }
                        hf_ConId.Value = detId.TrimEnd('|');
                        //编辑前的已购数量=卡片数量+备品数量+赠品数量
                        hfEditSumCard.Value = dt.Rows[0]["deTotal"].ToString();
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (cData.IsSubmit == 0 || cData.IsSubmit == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }

                    //通过需求单ID得到需求总数量和已购合同总数量
                    DataTable condt = CardLogistics.DAL.CommonData.GetList("*", "v_purchase_demand", "ID='" + cData.DEMANDID + "'");
                    if (condt.Rows.Count > 0)
                    {
                        DemandCardTotal.Value = condt.Rows[0]["CardTotal"].ToString(); //需求总数量
                        ConCardTotal.Value = condt.Rows[0]["ConTotal"].ToString();//已购合同数量
                    }
                    TitleName = GetStatusInfo(cData.IsSubmit, "采购合同");
                }
            }
            else
            {
                hfEditSumCard.Value = "0";
                CONNO.Value = GetBillNumber("采购合同");
            }
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(0);
                ShowMegByResult(result, 0);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 保存并提交
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                ShowMegByResult(result, 1);
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        #endregion

        #region 提示信息
        /// <summary>
        /// 提示信息
        /// </summary>
        /// <param name="result"></param>
        private void ShowMegByResult(string result, int issubmit)
        {
            if (result.Split(',')[0] == "ok")
            {
                if (issubmit == 1)
                {
                    InsertAppInfo(1, result.Split(',')[1]);//采购合同审核信息
                    InsertLog("保存并提交合同信息,合同编号:" + CONNO.Value);
                }
                else
                    InsertLog("保存合同信息,合同编号:" + CONNO.Value);
                ReturnListInfo();
            }
            else
            {
                ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
            }
        }
        #endregion

        #region 得到合同实体
        /// <summary>
        /// 合同实体
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            string result = string.Empty;
            Purchase_Contract model = new Purchase_Contract();
            model = GetWebControls<Purchase_Contract>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.SUPPID = ddlSUPPID.Value;//供应商
            model.BUYTYPEID = ddlBUYTYPEID.Value;//采购类型
            model.DEMANDID = hf_DEMANDID.Value;//需求单id
            model.IsSubmit = issubmit;
           string  FileValue = hf_ConId.Value.TrimEnd('|'); //合同明细字段

            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model, FileValue);
            }
            else
            {
                result = DAL.Add(model, FileValue);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("采购合同");
                }
            }
            return result;
        }
        #endregion
    }
}